﻿using DataAccess.DTO;
using DataAccess.Solr;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace UrlShorten.Controllers
{
    public class HomeController : Controller
    {
     
        public ActionResult Index()
        {
            return Content("OK");
        }
        public ActionResult Skip(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                string Url=ShortenUrl.ParseUrl(new string[] { id })[0];
                if(string.IsNullOrEmpty(Url))
                    return Content("输入的URL地址有误！");
                if (Request.Headers["User-Agent"].IndexOf("MicroMessenger") > -1)
                {
                    try
                    {
                        Uri uri = new Uri(Url);
                        string queryString = uri.Query;
                        NameValueCollection col = GetQueryString(queryString);
                        string searchKey = col["itemId"];
                        ProductDetail model = new SolrIndexDetailBLL().GetProductDetailByProductInfo(searchKey);
                        if (model != null)
                        {
                            Response.Write(string.Format("<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0\"><title>{0}</title></head><body><div class=\"wrapper zk-detail\"><div class=\"model-mask\"><img src=\"http://0d077ef9e74d8.cdn.sohucs.com/qn4Pkgq_png\"></div><div class=\"zk-pic-area\"><img src=\"{1}\" alt=\"\"></div><p class=\"zk-title\">{0}</p><p class=\"zk-ori-price\">&yen;{2}</p><p class=\"zk-stat\"><span class=\"quan\">券后价</span> <span class=\"number-font\"><em class=\"yen\">&yen;</em><em class=\"zk-price\">{3}</em></span></p><a href=\"\"><div class=\"zk-buy-area\"><p class=\"coupon-desc\">领券立省{4}元</p><p class=\"btn\">立即领券</p></div></a></div><style>html,body,div,span,applet,em,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a{{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:none}}.wrapper{{padding-top:0px;position:relative;width:100%;min-width:320px;max-width:640px;margin:0 auto}}.zk-detail{{position:relative;background-color:#fff}}.zk-detail .zk-pic-area{{position:relative}}.zk-detail .zk-pic-area img{{width:100%}}.zk-detail .zk-title{{font-size:16px;line-height:26px;color:#444;padding:5px 10px}}.zk-detail .zk-ori-price{{font-size:16px;color:#666;line-height:23px;padding-left:10px;text-decoration:line-through}}.zk-detail .zk-stat{{position:relative;height:24px;padding:5px 10px 0}}.zk-detail .zk-stat .quan{{position:relative;float:left;display:inline-block;width:72px;height:24px;font-size:13px;color:#fff;text-align:center;line-height:24px;background-color:#FD6363;margin-right:10px;border-radius:1px}}.zk-detail .zk-stat .quan:after{{position:absolute;display:table;content:'';width:0;height:0;border:4px solid transparent;border-left-color:#FD6363;right:-8px;top:50%;margin-top:-4px}}.zk-detail .zk-stat .number-font{{float:left;display:inline-block;color:#FD6363;height:24px}}.zk-detail .zk-stat .number-font .yen{{font-size:18px;line-height:24px;height:24px;vertical-align:bottom}}.zk-detail .zk-stat .number-font .zk-price{{font-size:28px;padding-left:3px;position:relative;top:2px}}.zk-detail .zk-buy-area{{margin:20px 10px;height:56px;background-color:#FD6363;border-radius:2px}}.zk-detail .zk-buy-area .coupon-desc{{float:left;font-size:16px;color:#fff;line-height:56px;padding-left:15px}}.zk-detail .zk-buy-area .btn{{float:right;margin:16px 15px 0 0;height:24px;width:88px;border:1px solid #fff;border-radius:2px;background-color:#ec5252;font-size:14px;color:#fff;line-height:24px;text-align:center;padding:0}}.zk-detail .hot-zk-list{{background-color:#f8f8f8;padding:0 10px 10px}}.zk-detail .hot-zk-list .head{{font-size:14px;color:#666;text-align:center;line-height:20px;height:20px;padding:15px 0 5px}}.model-mask{{position:fixed;width:100%;height:100%;background-color:rgba(0,0,0,.7);z-index:9999}}.model-mask img{{width:100%}}*{{-webkit-user-select:none;-webkit-touch-callout:none}}body{{background-color:#f8f8f8}}body{{line-height:1;font-family:\"PingFang SC\",PingFangRegular,华文黑体,\"Microsoft YaHei\",微软雅黑,\"Heiti SC\",\"San Francisco\",Helvetica;color:#666;font-size:14px;background-color:#f0f0f0}}</style></body></html>", model.title, model.pictUrl, model.zkPrice, (model.zkPrice - model.couponAmount), model.couponAmount));
                            Response.End();
                        }
                    }
                    catch (Exception)
                    {
                        return Content("输入的URL地址有误！");
                    }
                    return null;
                }
                return Redirect(Url);
            }
            return null;
        }


        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.Replace("?", "");
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }
        public ActionResult Surl(string Url)
        {
            if(!string.IsNullOrEmpty(Url))
            {
                return Content(ShortenUrl.AddUrl(new string[] { Url })[0]);
            }
            return null;
        }
	}
}